<!--变更订单-->
<template>
    <div>上传文件
        <input id="img" type="file" accept="image/*" @change="afterRead($event)">
        <img id="downImg"/>
<!--        <el-upload-->
<!--            list-type="picture-card"-->
<!--            :on-preview="handlePictureCardPreview"-->
<!--            :on-remove="handleRemove">-->
<!--            <i class="el-icon-plus"></i>-->
<!--        </el-upload>-->
        <el-dialog :visible.sync="dialogVisible">
            <img width="100%" :src="dialogImageUrl" alt="">
        </el-dialog>
    </div>
</template>
<script>
    // import { convertBase64UrlToFromData, photoCompress} from './imageCom'
    import {compressImage} from './imageCom'
    //最大高度

    const maxHeight = 500;

    //最大宽度

    const maxWidth = 500;
    export default {
        data() {
            return {
                dialogImageUrl: '',
                dialogVisible: false,
                baseImg: ''
            };
        },
        components: {},

        methods: {
            handleRemove(file, fileList) {
                console.log(file, fileList);
            },
            handlePictureCardPreview(file) {
                this.dialogImageUrl = file.url;
                this.dialogVisible = true;
            },
            //读取完图片后

            afterRead() {
                // const file = document.getElementById('file');
                let file = document.getElementById('img').files[0];
                // console.log('afterRead------', file);
                    const imgUrl = URL.createObjectURL(file);
                    const imgEle = document.createElement('img')
                    imgEle.src = imgUrl
                    imgEle.onload = function () {
                        const originHeight = imgEle.height;

                        const originWidth = imgEle.width;

                        let compressedWidth = imgEle.width;

                        let compressedHeight = imgEle.height;

                        if ((originWidth > maxWidth) && (originHeight > maxHeight)) {

                            // 更宽更高，

                            if ((originHeight / originWidth) > (maxHeight / maxWidth)) {

                                // 更加严重的高窄型，确定最大高，压缩宽度

                                compressedHeight = maxHeight

                                compressedWidth = maxHeight * (originWidth / originHeight)

                            } else {

                                //更加严重的矮宽型, 确定最大宽，压缩高度

                                compressedWidth = maxWidth

                                compressedHeight = maxWidth * (originHeight / originWidth)

                            }

                        } else if (originWidth > maxWidth && originHeight <= maxHeight) {

                            // 更宽，但比较矮，以maxWidth作为基准

                            compressedWidth = maxWidth

                            compressedHeight = maxWidth * (originHeight / originWidth)

                        } else if (originWidth <= maxWidth && originHeight > maxHeight) {

                            // 比较窄，但很高，取maxHight为基准

                            compressedHeight = maxHeight

                            compressedWidth = maxHeight * (originWidth / originHeight)

                        } else {

                            // 符合宽高限制，不做压缩

                        }

                        const canvas = document.createElement('canvas')
                        const ctx = canvas.getContext('2d')
                        canvas.width = compressedWidth
                        canvas.height = compressedHeight
                        ctx.clearRect(0, 0, compressedWidth, compressedHeight);
                        ctx.drawImage(imgEle, 0, 0,compressedWidth, compressedHeight)
                        const data = canvas.toDataURL('image/jpeg', 0.2)
                        const downImg = document.getElementById('downImg')
                        downImg.href = data
                        this.baseImg = data
                    }
                this.base64toFile(this.baseImg);
                // this.getObjectURL(file);

            },
            base64toFile (dataurl, filename = 'file') {
                let arr = dataurl.split(',')
                let mime = arr[0].match(/:(.*?);/)[1]
                let suffix = mime.split('/')[1]
                let bstr = atob(arr[1])
                let n = bstr.length
                let u8arr = new Uint8Array(n)
                while (n--) {
                    u8arr[n] = bstr.charCodeAt(n)
                }
                let file =  new File([u8arr], `${filename}.${suffix}`, {
                    type: mime
                })
                console.log(file)
            },
            // base64toFile(data, fileName) {
            //     const dataArr = data.split(",");
            //     const byteString = atob(dataArr[1]);
            //     const options = {
            //         type: "image/jpeg",
            //         endings: "native"
            //     };
            //     const u8Arr = new Uint8Array(byteString.length);
            //     for (let i = 0; i < byteString.length; i++) {
            //         u8Arr[i] = byteString.charCodeAt(i);
            //     }
            //     return new File([u8Arr], fileName + ".jpg", options);//返回文件流
            // },
            getObjectURL(file) {
                let url = null;
                if (window.createObjectURL != undefined) { // basic
                    url = window.createObjectURL(file);
                } else if (window.webkitURL != undefined) { // webkit or chrome
                    url = window.webkitURL.createObjectURL(file);
                } else if (window.URL != undefined) { // mozilla(firefox)
                    url = window.URL.createObjectURL(file);
                }
                // return url ;
                this._compressAndUploadFile(url);

            },
            //压缩图片上传

            _compressAndUploadFile(file) {

                compressImage(file).then(result => {

                    console.log('压缩后的结果', result); // result即为压缩后的结果

                    console.log('压缩前大小', file.file.size);

                    console.log('压缩后大小', result.size);

                    if (result.size > file.file.size) {

                        console.log('上传原图');

                        //压缩后比原来更大，则将原图上传

                        // this._uploadFile(file.file, file.file.name);

                    } else {

                        //压缩后比原来小，上传压缩后的

                        console.log('上传压缩图');

                        // this._uploadFile(result, file.file.name)

                    }

                })

            },

            //上传图片

            // _uploadFile(file, filename) {
            //
            //   let params = new FormData();
            //
            //   params.append("file", file, filename);
            //
            //   this.$api.uploadImage(params).then(res => {
            //
            //     console.log('uploadImage', res);
            //
            //     //上传成功，写自己的逻辑
            //
            //   }).catch(err => {
            //
            //     console.log('err', err);
            //
            //   });
            //
            // },

        }

    }
</script>
